package com.luo.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.luo.dao.OrderSettingDao;
import com.luo.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.util.*;

/**
 * @author Zoro
 * @date 2021年08月28
 */
@Transactional(readOnly = true)
@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    @Transactional(readOnly = false)
    public void insertList(List<String[]> datas) {
        for (String[] data : datas) {
            OrderSetting orderSetting = new OrderSetting(new Date(data[0]), Integer.parseInt(data[1]));
            OrderSetting oldOrderSetting = orderSettingDao.getOrderSetting(orderSetting.getOrderDate());
            if (oldOrderSetting != null) {
                orderSettingDao.updateOrderSetting(orderSetting);
            } else {
                orderSettingDao.insertOrderSetting(orderSetting);
            }
        }
    }

    @Override
    public List<Map<String, Integer>> getOrderSettingByMonth(String date) {
        List<OrderSetting> orderSettings = orderSettingDao.getOrderSettingByMonth(date);
        List<Map<String, Integer>> newOrders = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            HashMap<String, Integer> map = new HashMap(3);
            map.put("date", orderSetting.getOrderDate().getDate());
            map.put("number", orderSetting.getNumber());
            map.put("reservations", orderSetting.getReservations());
            newOrders.add(map);
        }
        return newOrders;
    }

    @Override
    @Transactional(readOnly = false)
    public void editNumberByDate(OrderSetting orderSetting) {
        OrderSetting oldOrderSetting = orderSettingDao.getOrderSetting(orderSetting.getOrderDate());
        if (oldOrderSetting == null) {
            orderSettingDao.insertOrderSetting(orderSetting);
        } else {
            //判断预约人数是否小于要修改的可预约人数
            if (oldOrderSetting.getReservations() > orderSetting.getNumber()) {
                throw new RuntimeException("修改失败，不符合");
            } else {
                orderSettingDao.updateOrderSetting(orderSetting);
            }
        }
    }
}
